//
//  CCCommentViewController.m
//  Activity
//
//  Created by its on 15/5/21.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCCommentViewController.h"
#import "MJRefresh.h"
#import "CCError.h"
#import "CCCommentTableViewCell.h"
#import <UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.h>
#import "DaiDodgeKeyboard.h"
#import <UITextView+Placeholder/UITextView+Placeholder.h>
@interface CCCommentViewController ()
@property (nonatomic, strong) CCCommentViewModel *viewModel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIToolbar *bar;
@property (nonatomic, strong) UITextView *textview;
@property (nonatomic, strong) UIButton *send;
@property (nonatomic, strong) RACDisposable *listDisposable;
@property (nonatomic, strong) RACDisposable *footDisposable;
@end

@implementation CCCommentViewController

- (id) initWithViewModel:(CCCommentViewModel *)viewModel {
  if ( self = [super init] ) {
    _viewModel = viewModel;
  }
  return self;
}
- (void)viewDidLoad {
  [self setTitleBar];
  [self setupBottomBar];
  [self bindUI];
  [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
}

- (void) viewDidAppear:(BOOL)animated {
//  [DaiDodgeKeyboard addRegisterTheViewNeedDodgeKeyboard:self.bar];
  [self addObservers];
  [super viewDidAppear:animated];
}

- (void) viewDidDisappear:(BOOL)animated {
//  [DaiDodgeKeyboard removeRegisterTheViewNeedDodgeKeyboard];
  [self removeObservers];
  [super viewDidDisappear:animated];
}

- (void) setTitleBar {
  self.title = @"评论";
  
  UIImage *image = IMAGE(@"back");
  image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:nil action:nil];
  @weakify(self);
  self.navigationItem.leftBarButtonItem.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    @strongify(self);
    [self.navigationController popViewControllerAnimated:YES];
    [self.listDisposable dispose];
    [self.footDisposable dispose];
    return [RACSignal empty];
  }];
  
  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"评论" style:UIBarButtonItemStylePlain target:nil action:nil];
  [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:RGB(255, 255, 255, 1)} forState:UIControlStateNormal];
  self.navigationItem.rightBarButtonItem.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    @strongify(self);
    self.viewModel.placehold = @"评论";
    self.viewModel.replyAuthor = self.viewModel.replyid = self.viewModel.replyName = nil;
    [self.textview becomeFirstResponder];
    return [RACSignal empty];
  }];
}

- (void) setupUI {
  _tableView  = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
  [_tableView registerClass:[CCCommentTableViewCell class] forCellReuseIdentifier:@"cell"];
  [_tableView registerClass:[CCCommentTableViewCell class] forCellReuseIdentifier:@"cell1"];
  _tableView.allowsSelection = NO;
  self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  self.tableView.estimatedRowHeight = 200;
  _tableView.delegate = self;
  _tableView.dataSource = self;
  self.viewModel.addTableView = YES;
  [self.view addSubview:self.tableView];

}

- (void) setupCSS {
  [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.view);
    make.right.equalTo(self.view);
    make.top.equalTo(self.view);
    make.bottom.equalTo(self.bar.mas_top);
  }];
}

- (void) setupBottomBar {
  _bar = [[UIToolbar alloc] initWithFrame:CGRectZero];
  _bar.barTintColor = RGB(244, 244, 244, 1);
  _bar.translucent = NO;
  _textview = [[UITextView alloc] initWithFrame:CGRectZero];
  _textview.font = [UIFont systemFontOfSize:15];
  _textview.layer.cornerRadius = 2.0f;
  _send = [UIButton buttonWithType:UIButtonTypeCustom];
  _textview.layer.borderWidth = 1.0f;
  _textview.layer.borderColor = [UIColor lightGrayColor].CGColor;
  [_send setTitle:@"发送" forState:UIControlStateNormal];
  [_send setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
  [self.view addSubview:_bar];
  [self.view addSubview:_tableView];
  [_bar addSubview: _textview];
  [_bar addSubview:_send];
  
  [self.bar mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.view);
    make.right.equalTo(self.view);
    make.bottom.equalTo(self.view);
    make.height.equalTo(@(40));
  }];
  
  [_textview mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.bar).offset(10);
    make.top.equalTo(self.bar).offset(3);
    make.bottom.equalTo(self.bar).offset(-3);
    make.right.equalTo(self.send.mas_leading).offset(-5);
  }];
  
  [_send mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.bar);
    make.right.equalTo(self.bar).offset(10);
    make.width.equalTo(@(80));
    make.height.equalTo(@(30));
  }];
  
  @weakify(self);
  _send.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    @strongify(self);
    [CCProgressHUD showHUBInView:[[UIApplication sharedApplication] windows][1] withTimeOut:0 str:nil];
    [(self.viewModel.replyid?[self.viewModel reply]:[self.viewModel publicComment]) subscribeNext:^(NSDictionary *x) {
      [CCProgressHUD hiddenHUBFromView:[[UIApplication sharedApplication] windows][1]];
      if ([(CCError *)x[@"error"] code] == 4001 || [(CCError *)x[@"error"] code] == 4002) {
        [CCRouter routerWithURL:@"login" param:@{@"controller": self}];
      } else {
        if (!self.viewModel.replyid) {
          [self.viewModel sendCommentMessage:x[@"objectid"]];
        }
        if ([(CCError *)x[@"error"] code] == 3000 && self.viewModel.addTableView) {
          [self.tableView reloadData];
        } else if ([(CCError *)x[@"error"] code] == 3000 && !self.viewModel.addTableView) {
          [self setupUI];
          [self setupCSS];
          [self setupTableView];
        }
        self.viewModel.replyName = self.viewModel.replyid = self.viewModel.replyAuthor = nil;
        self.textview.text = nil;
        self.viewModel.placehold = @"评论";
        [self.textview resignFirstResponder];
        [CCProgressHUD showMessageinWindow:2.0f str:[x[@"error"] des]];
      }
    }];
    return [RACSignal empty];
  }];
  
  RAC(self.viewModel, content) = self.textview.rac_textSignal;
  [RACObserve(self.viewModel, placehold) subscribeNext:^(id x) {
    @strongify(self);
    if (x != nil) {
      [self.textview becomeFirstResponder];
      self.textview.text = nil;
      self.textview.placeholder = [NSString stringWithFormat:@"回复%@:",x];
    } else {
      [self.textview resignFirstResponder];
      self.textview.placeholder = nil;
    }
  }];
  
}


- (void) bindUI {
  [CCProgressHUD showHUBInView:self.view withTimeOut:0 str:nil];
  self.listDisposable = [[_viewModel setViewModelActivity] subscribeNext:^(CCError *x) {
    if ( x.code == 3002 && !self.viewModel.addTableView ) {
      [self setupUI];
      [self setupCSS];
      [self setupTableView];
    } else if (x.code == 3002 && !self.viewModel.addTableView) {
      [self.tableView reloadData];
    } else {
      @weakify(self);
      [self showErrorView:x.des block:^{
        @strongify(self);
        [self bindUI];
      }];
    }
    [CCProgressHUD hiddenHUBFromView:self.view];
  }];
}

- (void) setupTableView {
  @weakify(self);
  [self.tableView addFooterWithCallback:^{
    @strongify(self);
    self.footDisposable = [[self.viewModel getFoot] subscribeNext:^(id x) {
      @strongify(self);
      if ( [x isKindOfClass:[CCError class]] ) {
        [CCProgressHUD showMessage:self.view withTimeOut:1.0f str:[(CCError *)x des]];
      } else {
        [self.tableView reloadData];
      }
    }];
    [self.tableView footerEndRefreshing ];
  }];
  
}

#pragma mark table datasource

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.row < self.viewModel.myCommentList.count) {
    CCCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
    CCComCellViewModel *viewModel = self.viewModel.myCommentList[indexPath.row];
    [cell bindWithViewModel:viewModel];
    return cell;
  } else {
    CCCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    CCComCellViewModel *viewModel = self.viewModel.listArray[indexPath.row-self.viewModel.myCommentList.count];
    [cell bindWithViewModel:viewModel];
    return cell;
  }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return  self.viewModel.listArray.count + self.viewModel.myCommentList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//  if (indexPath.row < self.viewModel.myCommentList.count) {
//    return [tableView fd_heightForCellWithIdentifier:@"cell1" configuration:^(id cell) {
//      CCComCellViewModel *viewModel = self.viewModel.myCommentList[indexPath.row];
//      [cell bindWithViewModel:viewModel];
//    }];
//  } else {
//    return [tableView fd_heightForCellWithIdentifier:@"cell" configuration:^(id cell) {
//      CCComCellViewModel *viewModel = self.viewModel.listArray[indexPath.row-self.viewModel.myCommentList.count];
//      [cell bindWithViewModel:viewModel];
//    }];
//  }
  if (indexPath.row < self.viewModel.myCommentList.count) {
      return [CCCommentTableViewCell getCellHeight: self.viewModel.myCommentList[indexPath.row]];
  } else {
      return [CCCommentTableViewCell getCellHeight: self.viewModel.listArray[indexPath.row]];
  }

}

#pragma mark table delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  [_textview resignFirstResponder];
}


#pragma mark keyboard 
- (void)addObservers
{
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeObservers
{
  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


- (void) keyboardWillShow:(NSNotification *)notification {
  CGRect keyboardBounds;
  [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
  NSNumber *duration = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
  NSNumber *curve = [notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
  
  keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
  
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationBeginsFromCurrentState:YES];
  [UIView setAnimationDuration:[duration doubleValue]];
  [UIView setAnimationCurve:[curve intValue]];
  [UIView setAnimationDelegate:self];
  
  // set views with new info
  [self.bar mas_remakeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.view);
    make.right.equalTo(self.view);
    make.bottom.equalTo(self.view).offset(-CGRectGetHeight(keyboardBounds));
    make.height.equalTo(@(40));
  }];
  [self.bar layoutIfNeeded];
  // commit animations
  [UIView commitAnimations];
  
  
}

- (void) keyboardWillHide:(NSNotification *)notification {
  NSNumber *duration = [notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
  NSNumber *curve = [notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
  
  // get a rect for the textView frame
  // animations settings
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationBeginsFromCurrentState:YES];
  [UIView setAnimationDuration:[duration doubleValue]];
  [UIView setAnimationCurve:[curve intValue]];
  [self.bar mas_remakeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.view);
    make.right.equalTo(self.view);
    make.bottom.equalTo(self.view);
    make.height.equalTo(@(40));
  }];
  [self.bar layoutIfNeeded];
  
  // commit animations
  [UIView commitAnimations];
}

- (void) dealloc {
  
}
@end
